#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time     : 2024/4/21 1:08
# @Author   : MingTai
# @File     : router_demo_controller.py
import json
from datetime import datetime

from flask import request

from app.business.mysql_init.init_sql_alchemy import creat_app
from app.business.sql_demo import sql_insert_choice

flask_app = creat_app()


@flask_app.route('/')
def demo_controller():
    return {
        'hello': 'world',
        'success': 'ok1',
        'current_time ': datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')
    }


@flask_app.route('/sql_insert')
def sql_insert_controller():
    aaa = sql_insert_choice.insert_user_if_not_none(username='lier', email='777@163.com', age=19)
    return {
        'hello': 'world',
        'success': 'ok1',
        'current_time ': datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')
    }


# 路由校要前后都加上 / 在请求时，加不加/都能找到对应的路由
@flask_app.route('/sql_select/')
def sql_select_controller():
    user_list = sql_insert_choice.select_user()
    return {
        'hello': 'world',
        'success': 'ok1',
        'current_time ': datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S'),
        'user_list': user_list
    }


@flask_app.route('/sql_update/')
def sql_update_controller():
    user_list = sql_insert_choice.update_user()
    return {
        'hello': 'world',
        'success': 'ok1',
        'current_time ': datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S'),
        'user_list': user_list
    }


@flask_app.route('/request_data')
def request_data_controller():
    # get请求参数可以接收
    foo1 = request.values.get('aa')
    foo2 = request.args.get('bb')
    # get请求处理接收不了的参数
    foo3 = request.data.decode(encoding='utf8')
    print(foo1)
    print(foo2)
    print(foo3)
    return {
        'hello': 'world',
        'success': 'ok1',
        'current_time ': datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')
    }


@flask_app.route('/post_request', methods=['POST'])
def post_request_controller():
    # 可以接收post请求的参数
    foo1 = request.values.get('aa')
    foo2 = request.args.get('bb')
    # 接收一个JSON字符串，decode以后是一个字符串，需要反序列化成Python dic
    foo3 = request.data.decode(encoding='utf8')

    # 请求传参，接收后，直接转换为dic类型，
    foo4 = request.json
    print(foo1)
    print(foo2)
    print(foo3)
    print(f'foo3 json = {json.loads(foo3)}')
    print(foo4)
    return {
        'hello': 'world',
        'success': 'ok1',
        'current_time ': datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')
    }


@flask_app.route('/two_request', methods=['POST', 'GET'])
def two_request_controller():
    # 两个请求一起，这两种无法接受JSON字符串的请求，无论是get还是post
    foo1 = request.values.get('aa')
    foo2 = request.args.get('bb')

    print(foo1)
    print(foo2)
    return {
        'hello': 'world',
        'success': 'ok1',
        'current_time ': datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')
    }
